#include "server.h"
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
// #include "protocol_examples_common.h"
#include "data.h"
#include "cJSON.h"
#include <esp_wifi.h>
#include <esp_event.h>
#include <esp_log.h>
#include <esp_system.h>
#include <nvs_flash.h>
#include <sys/param.h>
#include "nvs_flash.h"
#include "esp_netif.h"
#include "esp_eth.h"
#include "esp_tls_crypto.h"

#include "ledc.h"
#include "led_color.h"

static const char *TAG = "server";

unsigned char r,g,b;

/* 定义HTTP GET处理函数 */
esp_err_t hello_get_handler(httpd_req_t *req) {
    // 设置Content-Type头部信息为"text/html; charset=utf-8"
    httpd_resp_set_type(req, "text/html");
    // httpd_resp_set_charset(req, "UTF-8");

    // 发送HTML响应
    httpd_resp_send(req, data, sizeof(data) - 1); // 注意减去1，确保不发送字符串末尾的null字符
    // httpd_resp_send(req, data, sizeof(data));
    ESP_LOGI(TAG, "Get html success!");
    return ESP_OK;  
}

/* 定义HTTP GET处理函数 */
esp_err_t image_get_handler(httpd_req_t *req) {
    // const char *resp_str = "Hello, ESP32!";
    httpd_resp_send(req, image_data, sizeof(image_data));
    return ESP_OK;  
}

/* 定义HTTP POST处理函数：同步颜色值 */
esp_err_t sync_color_value_post_handler(httpd_req_t *req) {
    char buf[100];
    int ret, remaining = req->content_len;

    if (remaining > sizeof(buf)) {
        /* 数据太长 */
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too long");
        return ESP_FAIL;
    }

    while (remaining > 0) {
        /* 读取请求数据 */
        ret = httpd_req_recv(req, buf, sizeof(buf));
        if (ret <= 0) {
            /* 读取错误或结束 */
            if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
                /* 超时错误 */
                httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "Receive timeout");
            }
            return ESP_FAIL;
        }
        remaining -= ret;
    }

    /* 处理请求数据 */
    cJSON *json = cJSON_Parse(buf);
    if (json != NULL) {
        cJSON *color_value = cJSON_GetObjectItem(json, "color");
        if (color_value != NULL) {
            /* 从请求数据中获取颜色值，并进行相应操作 */
            const char *selected_color = color_value->valuestring;
            ESP_LOGI(TAG, "Selected color :%s",selected_color);
            // 在这里处理颜色值
            convertColorString(selected_color,&r,&g,&b);
            ESP_LOGI(TAG,"红色：%02x, 绿色：%02x, 蓝色：%02x\n", r, g, b);
            ledc_set_RGB(r,g,b);
        }
        cJSON_Delete(json);
    }

    /* 响应请求 */
    const char *resp_str = "{\"status\": \"success\"}";
    httpd_resp_send(req, resp_str, strlen(resp_str));
    return ESP_OK;
}

/* 定义HTTP POST处理函数：同步定时器值 */
esp_err_t sync_timer_value_post_handler(httpd_req_t *req) {
    char buf[100];
    int ret, remaining = req->content_len;

    if (remaining > sizeof(buf)) {
        /* 数据太长 */
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too long");
        return ESP_FAIL;
    }

    while (remaining > 0) {
        /* 读取请求数据 */
        ret = httpd_req_recv(req, buf, sizeof(buf));
        if (ret <= 0) {
            /* 读取错误或结束 */
            if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
                /* 超时错误 */
                httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "Receive timeout");
            }
            return ESP_FAIL;
        }
        remaining -= ret;
    }

    /* 处理请求数据 */
    cJSON *json = cJSON_Parse(buf);
    if (json != NULL) {
        cJSON *timer_value = cJSON_GetObjectItem(json, "selectedTime");
        if (timer_value != NULL) {
            /* 从请求数据中获取定时器值，并进行相应操作 */
            const char *selected_time = timer_value->valuestring;
            // 在这里处理定时器值
            ESP_LOGI(TAG, "Selected time :%s",selected_time);
            char *endptr;
            unsigned long int num = strtoul(selected_time, &endptr, 10);

            if (endptr == selected_time) {
                // 转换失败
                ESP_LOGI(TAG, "转换失败，无法解析数字。\n");
            } else {
                set_led_off_time(num);
            }     
        }
        cJSON_Delete(json);
    }

    /* 响应请求 */
    const char *resp_str = "{\"status\": \"success\"}";
    httpd_resp_send(req, resp_str, strlen(resp_str));
    return ESP_OK;
}

/* 定义HTTP POST处理函数：同步LED状态 */
esp_err_t sync_light_status_post_handler(httpd_req_t *req) {
    char buf[100];
    int ret, remaining = req->content_len;

    if (remaining > sizeof(buf)) {
        /* 数据太长 */
        httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "Content too long");
        return ESP_FAIL;
    }

    while (remaining > 0) {
        /* 读取请求数据 */
        ret = httpd_req_recv(req, buf, sizeof(buf));
        if (ret <= 0) {
            /* 读取错误或结束 */
            if (ret == HTTPD_SOCK_ERR_TIMEOUT) {
                /* 超时错误 */
                httpd_resp_send_err(req, HTTPD_408_REQ_TIMEOUT, "Receive timeout");
            }
            return ESP_FAIL;
        }
        remaining -= ret;
    }

    /* 处理请求数据 */
    cJSON *json = cJSON_Parse(buf);
    if (json != NULL) {
        cJSON *led_state_item = cJSON_GetObjectItem(json, "isOn");
        if (led_state_item != NULL) {
            /* 从请求数据中获取LED状态，并进行相应操作 */
            bool is_on = cJSON_IsTrue(led_state_item);
            ESP_LOGI(TAG, "Recive led state : %d",is_on);
            set_led_status(is_on);
        }
        cJSON_Delete(json);
    }

    /* 响应请求 */
    const char *resp_str = "{\"status\": \"success\"}";
    httpd_resp_send(req, resp_str, strlen(resp_str));
    return ESP_OK;
}

/* 定义HTTP GET处理函数：获取LED状态 */
esp_err_t get_light_status_get_handler(httpd_req_t *req) {
    bool is_on = get_led_status();

    /* 响应请求 */
    cJSON *json = cJSON_CreateObject();
    cJSON_AddBoolToObject(json, "isOn", is_on);
    const char *resp_str = cJSON_Print(json);
    cJSON_Delete(json);
    ESP_LOGI(TAG, "Send led state : %d",is_on);
    httpd_resp_send(req, resp_str, strlen(resp_str));
    free((void *)resp_str);

    return ESP_OK;
}

/* 定义HTTP GET处理函数：获取当前灯颜色 */
esp_err_t get_current_color_get_handler(httpd_req_t *req) {
    // 创建JSON对象并添加当前灯颜色的RGB值
    led_color_t color = get_led_color();
    cJSON *json = cJSON_CreateObject();
    cJSON_AddNumberToObject(json, "r", color.r);
    cJSON_AddNumberToObject(json, "g", color.g);
    cJSON_AddNumberToObject(json, "b", color.b);

    // 将JSON对象转换为字符串
    char *json_str = cJSON_Print(json);
    cJSON_Delete(json);

    // 响应请求
    httpd_resp_set_type(req, "application/json");
    httpd_resp_send(req, json_str, strlen(json_str));
    free(json_str);

    return ESP_OK;
}

/* 定义HTTP GET处理函数：获取当前定时时间 */
esp_err_t get_timer_value_get_handler(httpd_req_t *req) {
    // 响应请求
    cJSON *json = cJSON_CreateObject();
    unsigned char time = get_led_off_time();
    cJSON_AddNumberToObject(json, "timerValue",time);
    const char *resp_str = cJSON_Print(json);
    cJSON_Delete(json);
    ESP_LOGI(TAG, "Send timer value : %d",time);
    httpd_resp_send(req, resp_str, strlen(resp_str));
    free((void *)resp_str);
    return ESP_OK;
}


/* URI和处理函数的映射 */
httpd_uri_t hello = {
    .uri       = "/",
    .method    = HTTP_GET,
    .handler   = hello_get_handler,
    .user_ctx  = NULL
};

httpd_uri_t get_image = {
    .uri       = "/003.jpg",
    .method    = HTTP_GET,
    .handler   = image_get_handler,
    .user_ctx  = NULL
};

httpd_uri_t sync_color_value = {
    .uri       = "/sync-color-value",
    .method    = HTTP_POST,
    .handler   = sync_color_value_post_handler,
    .user_ctx  = NULL
};

httpd_uri_t sync_timer_value = {
    .uri       = "/sync-timer-value",
    .method    = HTTP_POST,
    .handler   = sync_timer_value_post_handler,
    .user_ctx  = NULL
};

httpd_uri_t sync_light_status = {
    .uri       = "/sync-light-status",
    .method    = HTTP_POST,
    .handler   = sync_light_status_post_handler,
    .user_ctx  = NULL
};

httpd_uri_t get_light_status = {
    .uri       = "/get-light-status",
    .method    = HTTP_GET,
    .handler   = get_light_status_get_handler,
    .user_ctx  = NULL
};

httpd_uri_t get_current_color = {
    .uri       = "/get-current-color",
    .method    = HTTP_GET,
    .handler   = get_current_color_get_handler,
    .user_ctx  = NULL
};

/* URI和处理函数的映射 */
httpd_uri_t get_timer_value = {
    .uri       = "/get-timer-value",
    .method    = HTTP_GET,
    .handler   = get_timer_value_get_handler,
    .user_ctx  = NULL
};

/* 初始化HTTP服务器 */
httpd_handle_t start_webserver(void)
{
    httpd_handle_t server = NULL;
    httpd_config_t config = HTTPD_DEFAULT_CONFIG();

    // 启动HTTP服务器
    if (httpd_start(&server, &config) != ESP_OK) {
        printf("启动HTTP服务器失败");
        return NULL;
    }

    // 注册URI和处理函数
    httpd_register_uri_handler(server, &hello);
    httpd_register_uri_handler(server, &get_image);
    httpd_register_uri_handler(server, &sync_color_value);
    httpd_register_uri_handler(server, &sync_timer_value);
    httpd_register_uri_handler(server, &sync_light_status);
    httpd_register_uri_handler(server, &get_light_status);
    httpd_register_uri_handler(server, &get_current_color);
    httpd_register_uri_handler(server, &get_timer_value);

    ESP_LOGI(TAG,"启动HTTP服务器成功");

    return server;
}

/* 停止HTTP服务器 */
void stop_webserver(httpd_handle_t server)
{
    // 停止HTTP服务器
    httpd_stop(server);
    ESP_LOGI(TAG,"停止HTTP服务器");
}